package com.game.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.game.dao.IUserDao;
import com.game.pojo.User;
/**
 * 用户dao实现类
 * @author Administrator
 *
 */
public class UserDao implements IUserDao {
	//注入持久化上下文
	@PersistenceContext(unitName="mms_persistence_guessnumber")
	EntityManager entityManager;
	
	/**
	 * 根据openId查找User
	 */
	@Override
	public User getUserByOpenId(String openId) {
		List<User> resultList = entityManager.createQuery("select u from User u where u.openId = :openId")
						.setParameter("openId", openId).getResultList();
		if(resultList != null && resultList.size()>0){
			return resultList.get(0);
		}else{
			return null;
		}
	}
	
	/**
	 * 保存用户信息到数据库
	 */
	@Override
	public void saveUser(User user) {
		entityManager.persist(user);
		
	}
	
	/**
	 * 根据openId删除用户
	 */
	@Override
	public void deleteUser(String openId) {
		//先查处理User
		List<User> list = entityManager.createQuery("select u from User u where u.openId = :openId")
						.setParameter("openId", openId).getResultList();
		//再删除用户
		for (User user : list) {
			entityManager.remove(user);
		}
		
	}
	
}
